package rmhc.api.fb
{
	import flash.events.Event;
	
	import rmhc.api.ApiWrapper;
	import rmhc.api.dataflow.UserInfo;
	import rmhc.api.tasks.IGetFriends;
	
	public class GetFriends extends FbApiTask implements IGetFriends
	{
		public const BIG_LIMIT:int = 100;
		protected var gf:FbApiTask;
		protected var gt:GetIdsThumbs;
		
		protected var ids:Array;
		protected var friends:Vector.<UserInfo>;
		
		public function GetFriends(wrapper:ApiWrapper)
		{
			super(wrapper , "me/friends" , { offset : 0 , limit : 10000 } );
		}
		
		override public function parseData(result:Object, fail:Object=null):void
		{
			//теперь получаем инфу для всех
			ids = new Array();
			for each ( var o:Object in result )
			{
				ids.push( o.id );
			}
			var p:Object = { ids : ids.join("," ) , fields : "id,first_name,last_name,gender,picture" , offset : 0 , limit : 10000 };
			gf = new FbApiTask( wrapper , null , p );
			gf.addEventListener(Event.COMPLETE , onGetFriends );
			gf.run();
		}
		protected function onGetFriends( e:Event ):void
		{
			friends = new Vector.<UserInfo>();
			var raw:Object = gf.getRawData();
			var u:UserInfo;
			for each ( var f:Object in raw )
			{
				u = parseUserInfo( f );
				//trace( "friend" , u );
				friends.push( u );
			}
			
			//теперь получаем аватарки юзеров
			if ( friends.length < BIG_LIMIT )
			{
				//если много юзеров, то используем picture, если <BIG_LIMIT - получаем картинки
				gt = new GetIdsThumbs( wrapper , ids );
				gt.addEventListener( Event.COMPLETE , onGetThumbs );
				gt.run();
			}
			else
			{
				onComplete();
			}
		}
		protected function onGetThumbs( e:Event ):void
		{
			for each ( var u:UserInfo in friends )
			{
				u.thumbSrc = gt.getThumbSrc( u.uid );
			}
			onComplete();
		}
		
		public function getFriends():Vector.<UserInfo>
		{
			return friends;
		}
	}
}